﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KZ400B
{
    //校验
    public class Verify
    {
        public static int Compute(string data, ref byte code1, ref byte code2)
        {
            if (string.IsNullOrEmpty(data))
            {
                return ErrorCode.NoData;
            }
            return Compute(HexCon.StringToByteArray(data), ref code1, ref code2);
        }

        /// <summary>
        /// 计算校验码(各位加到一起后取16进制的最低两位)
        /// </summary>
        /// <param name="data"></param>
        /// <param name="code1"></param>
        /// <param name="code2"></param>
        /// <returns></returns>
        public static int Compute(byte[] data, ref byte code1, ref byte code2)
        {
            if (data == null || data.Length <= 0)
            {
                return ErrorCode.NoData;
            }
            int vCode = 0;
            foreach (byte bData in data)
            {
                vCode += bData;
            }
            code1 = (byte)(0x40 + ((vCode & 0x000000f0) >> 4));
            code2 = (byte)(0x40 + (vCode & 0x0000000f) );
            
            return ErrorCode.Success;
        }

        public static bool IsVerify(string data, byte code1, byte code2)
        {
            return IsVerify(HexCon.StringToByteArray(data), code1, code2);
        }

        public static bool IsVerify(byte[] data, byte code1, byte code2)
        {
            byte vCode1 = 0;
            byte vCode2 = 0;
            if (Compute(data, ref vCode1, ref vCode2) == ErrorCode.Success)
            {
                return vCode1 == code1 && vCode2 == code2;
            }
            return false;
        }
    }
}
